import { ref } from 'vue'
import { defineStore } from 'pinia'
import {
  getCartList,
  addCart,
  delCartItem,
  togChecked,
  togItemNum
} from '@/api/cart.js'
import { getGoodsDetail } from '@/api/category'
export const useCartStore = defineStore(
  'cartGoods',
  () => {
    const cartList = ref([])
    const setCartList = async () => {
      const res = await getCartList()
      cartList.value = res.data
      totalPrice.value = await Promise.all(
        cartList.value
          .filter((item) => item.is_checked)
          .map((item) => getGoodsDetail(item.goods_id))
      ).then((res) =>
        res.reduce(
          (total, cur, index) =>
            total + cur.goods.price * cartList.value[index].num,
          0
        )
      )
    }

    const clearList = () => {
      cartList.value = []
      totalPrice.value = 0
    }

    const addCarts = async (obj) => {
      await addCart(obj)
      setCartList()
    }

    const togNum = async (id, num) => {
      await togItemNum(id, num)
      setCartList()
    }

    const togcheck = async (arr) => {
      await togChecked(arr)
      setCartList()
    }

    const delItem = async (id) => {
      await delCartItem(id)
      setCartList()
    }

    const totalPrice = ref(0)

    return {
      cartList,
      setCartList,
      addCarts,
      togNum,
      togcheck,
      delItem,
      totalPrice,
      clearList
    }
  },
  {
    persist: true
  }
)
